package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.ProductBean;
import com.project.bean.SellBean;
import com.project.bean.SellCarBean;
import com.project.bean.SellInfoBean;
import com.project.mapper.*;
import com.project.service.ISellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class SellServiceImpl implements ISellService {
    @Autowired
    private ISellMapper sellMapper;

    @Autowired
    private ISellCarMapper sellCarMapper;
    @Autowired
    private ISellInfoMapper sellInfoMapper;

    @Autowired
    private IProductMapper productMapper;

    @Autowired
    private IClientMapper clientMapper;
    @Override
    public void add(SellBean sell, Integer userId) {
        //1.先计算该用户销售车的 订单总价格 然后添加至销售对象
        Integer money = sellCarMapper.getTotalPrice(userId);
        sell.setTotalPrice(money);
        //2.完成销售对象 添加
        sellMapper.insert(sell);
        //3.查询登陆用户 销售车集合
        List<SellCarBean> sellCarList = sellCarMapper.findByUserId(userId);
        // 4.将销售车集合 添加至销售车明细
        for (SellCarBean sellCar : sellCarList) {
            SellInfoBean sellInfoBean = new SellInfoBean();
            sellInfoBean.setNum(sellCar.getNum());
            sellInfoBean.setSellMoney(sellCar.getProduct().getSellPrice());
            sellInfoBean.setSellId(sell.getId());
            sellInfoBean.setProductId(sellCar.getProductId());
            sellInfoMapper.insert(sellInfoBean);
            //修改商品数量
            ProductBean product = productMapper.selectById(sellCar.getProductId());
            product.setNum(product.getNum() - sellCar.getNum());
            productMapper.updateById(product);
        }
        //5.添加成功后 清空销售车
        QueryWrapper<SellCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", userId);
        sellCarMapper.delete(qw);

    }

    @Override
    public IPage<SellBean> findByItem(Integer pageNO, String name, LocalDate startDate, LocalDate endDate) {
        return sellMapper.findByItem(new Page<>(pageNO, 5), name, startDate, endDate);
    }

    @Override
    public SellBean findById(Integer sellId) {
        SellBean sellBean = sellMapper.selectById(sellId);

        sellBean.setClientBean(clientMapper.selectById(sellBean.getClientId()));

        QueryWrapper<SellInfoBean> qw = new QueryWrapper<>();
        qw.eq("fk_sellId", sellId);
        List<SellInfoBean> sellInfoBeans = sellInfoMapper.selectList(qw);
        sellInfoBeans.forEach(e -> {
            e.setProduct(productMapper.selectById(e.getProductId()));
        });
        sellBean.setSellInfoList(sellInfoBeans);
        return sellBean;
    }
}
